using System;
using System.Web.UI.WebControls;
using Resources;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;
using System.Collections.Generic;

namespace Wicresoft.RDW.UserControls
{
    public partial class VisitRequestControl : System.Web.UI.UserControl
    {
        private static bool flag = false;
        public int LabId
        {
            get
            {
                if (ViewState["LabId"] == null)
                    return 0;
                return Convert.ToInt32(ViewState["LabId"]);
            }
            set
            {
                ViewState["LabId"] = value;
                InitProductList(value);
            }
        }
        public string Language
        {
            get { return BasePage.Language.ToString(); }
        }
        protected BasePage BasePage
        {
            get
            {
                return this.Page as BasePage;
            }
        }
        public Model.VisitRequest VisitRequestData
        {
            get
            {
                int visitType2 = 0;
                int visitType1Id = string.IsNullOrEmpty(ddlVisitType1.SelectedValue) ? 0 : Convert.ToInt32(ddlVisitType1.SelectedValue);
                var visitType1 = VisitTypePresent.GetById(visitType1Id);
                if (visitType1 != null)
                {
                    if (visitType1.ParentId != 0)
                    {
                        visitType2 = visitType1.ParentId;
                    }
                    else
                    {
                        visitType2 = string.IsNullOrEmpty(ddlVisitType2.SelectedValue) ? 0 : Convert.ToInt32(ddlVisitType2.SelectedValue);
                    }
                }
                int personNumber;
                bool result = int.TryParse(txtPersonNumber.Text, out personNumber);

                Model.VisitRequest data = new Model.VisitRequest()
                {
                    CompanyName = txtCompanyName.Text,
                    PersonNum = personNumber,
                    VisitType1 = string.IsNullOrEmpty(ddlVisitType1.SelectedValue) ? 0 : Convert.ToInt32(ddlVisitType1.SelectedValue),
                    VisitType2 = visitType2,
                    MainPersonName = txtPerson1Name.Text.Trim(),
                    MainPersonTitle = txtPerson1Title.Text.Trim(),
                    Person2Name = txtPerson2Name.Text.Trim(),
                    Person2Title = txtPerson2Title.Text.Trim(),
                    Person3Name = txtPerson3Name.Text.Trim(),
                    Person3Title = txtPerson3Title.Text.Trim(),
                    IsFirstTime = rbtnListIsFirst.Items[0].Selected,
                    Purpose = Server.HtmlEncode(txtPurpose.Text),
                    KeyContent = Server.HtmlEncode(txtKeyContent.Text),
                    OtherRequirements = Server.HtmlEncode(txtOtherRequirments.Text),
                    Accompany = string.IsNullOrEmpty(hfAccompanyId.Text) ? 0 : Convert.ToInt32(hfAccompanyId.Text),
                    AccompanyManager = txtAccompanyManager.Text.Trim(),
                    AccompanyManagerTitle = txtAccompanyManagerTitle.Text.Trim(),
                };
                if (!string.IsNullOrEmpty(hfVisitRequestId.Value))
                {
                    data.VisitRequestId = Convert.ToInt32(hfVisitRequestId.Value);
                }
                else
                {
                    data.VisitRequestId = 0;
                }

                if (rbtnListIsFirst.Items[1].Selected)
                {
                    //data.LastDate = Convert.ToDateTime(txtLastDate.Text);
                    var lastDate = DateTime.Today;
                    DateTime.TryParse(txtLastDate.Text, out lastDate);
                    if (lastDate != new DateTime())
                    {
                        data.LastDate = lastDate;
                    }
                }
                if (BasePage.Id == 0)
                {
                    for (int i = 0; i < VisitProductData.Count; i++)
                    {
                        if (VisitProductData[i] != null)
                        {
                            data.VisitProduct.Add(VisitProductData[i]);
                        }
                    }
                }
                data.RequestId = BasePage.Id;
                return data;
            }
        }
        public void VisitProductUpdate()
        {
            var request = RequestPresent.GetById(BasePage.Id);
            var visitRequest = VisitRequestPresent.GetByCondition(p => p.RequestId == BasePage.Id);
            var visitProductList = VisitProductPresent.GetList(p => p.VisitRequestId == visitRequest.VisitRequestId);
            if (visitProductList.Count != 0)
            {
                VisitProductPresent.Delete(visitProductList);
            }
            for (int i = 0; i < VisitProductData.Count; i++)
            {
                if (VisitProductData[i] != null)
                {
                    VisitProductData[i].VisitRequestId = visitRequest.VisitRequestId;
                    VisitProductPresent.Create(VisitProductData[i]);
                }
            }
        }

        public List<Model.VisitProduct> VisitProductData
        {
            get
            {
                List<Model.VisitProduct> VisitProduct = new List<Model.VisitProduct>();
                int visitRequestId = 0;
                if (BasePage.Id != 0)
                {
                    var visitRequest = VisitRequestPresent.GetByCondition(p => p.RequestId == BasePage.Id);
                    visitRequestId = visitRequest.VisitRequestId;
                }

                for (int i = 0; i < ckbProduct.Items.Count; i++)
                {
                    if (ckbProduct.Items[i].Selected)
                    {
                        VisitProduct.Add(new Model.VisitProduct()
                        {
                            VisitRequestId = visitRequestId,
                            ProductId = int.Parse(ckbProduct.Items[i].Value)
                        });
                    }

                }
                return VisitProduct;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int accompanyId;
            int.TryParse(hfAccompanyId.Text, out accompanyId);
            if (accompanyId != 0)
            {
                if (chkSame.Checked == true)
                {
                    txtAccompany.Attributes.Add("disabled", "disabled");
                }
                else
                {
                    txtAccompany.Attributes.Remove("disabled");
                }
                var accompany = UserPresent.GetById(accompanyId);
                txtAccompanyName.Text = BasePage.Language.ToString() == "CN" ? accompany.NameCN : accompany.NameEN;
                txtAccompanyDep.Text = accompany.BD;
                txtAccompanyCellphone.Text = accompany.Mobile;
                txtAccompanyTelephone.Text = accompany.OfficePhone;
                txtAccompanyEmail.Text = accompany.Email;
            }
            if (rbtnListIsFirst.Items[0].Selected)
            {
                txtLastDate.Attributes.Add("disabled", "disabled");
            }
            else
            {
                txtLastDate.Attributes.Remove("disabled");
            }
            if (!IsPostBack)
            {
                if (BasePage.PageStatus == PageStatus.Readonly)
                {
                    Wicresoft.RDW.Utility.Helper.ControlEditable(this, false);
                }
                else
                {
                    Wicresoft.RDW.Utility.Helper.ControlEditable(this, true);
                }
                InitResource();
                InitControl();
                LoadData();
            }

        }
        protected void InitResource()
        {
            chkSame.Text = NameResource.ckSame;
            //rfvAccompanyName.ErrorMessage = NameResource.User_Name + CommonResource.NotNull;
            rfvAccompanyManager.ErrorMessage = NameResource.VisitRequest_AccompanyManager + CommonResource.NotNull;
            rfvAccompanyManagerTitle.ErrorMessage = NameResource.VisitRequest_AccompanyManagerTitle + CommonResource.NotNull;

            rfvCompanyName.ErrorMessage = NameResource.VisitRequest_CompanyName + CommonResource.NotNull;
            rfvPersonNumber.ErrorMessage = NameResource.VisitRequest_PersonNum + CommonResource.NotNull;
            rfvVisitType1.ErrorMessage = NameResource.VisitRequest_VisitorType + CommonResource.NotNull;
            rfvPurpose.ErrorMessage = NameResource.VisitRequest_Purpose + CommonResource.NotNull;
            rfvPerson1Name.ErrorMessage = NameResource.VisitRequest_PersonName + CommonResource.NotNull;
            rfvtxtPerson1Title.ErrorMessage = NameResource.VisitRequest_PersonTitle + CommonResource.NotNull;
            rvPersonNumber.ErrorMessage = NameResource.VisitRequest_PersonNum + CommonResource.ErrorFormat;


        }
        protected void InitControl()
        {
            //Load Current User
            Model.User user = new Model.User();
            if (BasePage.Id != 0)
            {
                var request = RequestPresent.GetById(BasePage.Id);
                user = UserPresent.GetById(request.RequestUserId);
                txtUserId.Text = user.UserId.ToString();
            }
            else
            {
                txtUserId.Text = BasePage.CurrentUserId.ToString();
                user = UserPresent.GetById(BasePage.CurrentUserId);
            }

            if (user != null)
            {
                txtUserName.Text = BasePage.Language.ToString() == "CN" ? user.NameCN : user.NameEN;
                txtDep.Text = user.BD;
                txtCellphone.Text = user.Mobile;
                txtTelephone.Text = user.OfficePhone;
                txtEmail.Text = user.Email;
                txtUserName.ReadOnly = true;
                txtDep.ReadOnly = true;
                txtCellphone.ReadOnly = true;
                txtTelephone.ReadOnly = true;
                txtEmail.ReadOnly = true;
                txtAccompanyName.ReadOnly = true;
                txtAccompanyDep.ReadOnly = true;
                txtAccompanyCellphone.ReadOnly = true;
                txtAccompanyTelephone.ReadOnly = true;
                txtAccompanyEmail.ReadOnly = true;
            }
            ddlVisitType1.DataValueField = "Id";
            ddlVisitType1.DataTextField = BasePage.Language == Utility.Language.CN ? "Name_CN" : "Name_EN";
            ddlVisitType1.DataSource = VisitTypePresent.GetList(p => p.Level == 2);
            ddlVisitType1.DataBind();
            ddlVisitType1.Items.Insert(0, new ListItem(Resources.CommonResource.PleaseSelect, ""));

            ddlVisitType2.DataValueField = "Id";
            ddlVisitType2.DataTextField = BasePage.Language == Utility.Language.CN ? "Name_CN" : "Name_EN";
            ddlVisitType2.DataSource = VisitTypePresent.GetList(p => p.Level == 1);
            ddlVisitType2.DataBind();
            ddlVisitType2.Items.Insert(0, new ListItem(Resources.CommonResource.PleaseSelect, ""));
        }
        public void InitProductList(int labId)
        {
            ckbProduct.DataSource = ProductPresent.GetList(p => p.LabId == labId);
            ckbProduct.DataValueField = "ProductId";
            ckbProduct.DataTextField = BasePage.Language == Utility.Language.CN ? "Name_CN" : "Name_EN";
            ckbProduct.DataBind();
        }

        protected void LoadData()
        {

            if (BasePage.PageStatus == PageStatus.New)
                return;
            Model.VisitRequest visitRequest = VisitRequestPresent.GetByCondition(p => p.RequestId == BasePage.Id);
            if (visitRequest != null)
            {
                hfVisitRequestId.Value = visitRequest.VisitRequestId.ToString();

                Model.User accompany = UserPresent.GetById((int)visitRequest.Accompany);
                hfAccompanyId.Text = visitRequest.Accompany.ToString();
                if (accompany != null)
                {
                    if (visitRequest.Accompany == BasePage.CurrentUserId)
                    {
                        chkSame.Checked = true;
                        txtAccompany.Attributes.Add("disabled", "disabled");
                        txtAccompany.Text = NameResource.AccompanySearch;
                    }
                    else
                    {
                        txtAccompany.Text = accompany.Account;
                    }

                    txtAccompanyName.Text = BasePage.Language.ToString() == "CN" ? accompany.NameCN : accompany.NameEN;
                    txtAccompanyDep.Text = accompany.BD;
                    txtAccompanyCellphone.Text = accompany.Mobile;
                    txtAccompanyTelephone.Text = accompany.OfficePhone;
                    txtAccompanyEmail.Text = accompany.Email;
                }
                txtAccompanyManager.Text = visitRequest.AccompanyManager;
                txtAccompanyManagerTitle.Text = visitRequest.AccompanyManagerTitle;

                txtCompanyName.Text = visitRequest.CompanyName;
                txtPersonNumber.Text = visitRequest.PersonNum == 0 ? "" : visitRequest.PersonNum.ToString();
                ddlVisitType1.SelectedValue = visitRequest.VisitType1.ToString();
                ddlVisitType2.SelectedValue = visitRequest.VisitType2.ToString();

                txtPerson1Name.Text = visitRequest.MainPersonName;
                txtPerson1Title.Text = visitRequest.MainPersonTitle;
                txtPerson2Name.Text = visitRequest.Person2Name;
                txtPerson2Title.Text = visitRequest.Person2Title;
                txtPerson3Name.Text = visitRequest.Person3Name;
                txtPerson3Title.Text = visitRequest.Person3Title;
                if (!string.IsNullOrEmpty(visitRequest.Person2Name)
                    || !string.IsNullOrEmpty(visitRequest.Person3Name))
                {
                    phScript.Visible = true;
                }
                if (visitRequest.IsFirstTime)
                {
                    rbtnListIsFirst.Items[0].Selected = true;
                }
                else
                {
                    rbtnListIsFirst.Items[1].Selected = true;
                    txtLastDate.Text = Convert.ToDateTime(visitRequest.LastDate).ToString("yyyy-MM-dd");
                    if (BasePage.PageStatus != PageStatus.Readonly)
                    {
                        txtLastDate.Attributes.Remove("disabled");
                    }
                }

                txtOtherRequirments.Text = Server.HtmlDecode(visitRequest.OtherRequirements);
                txtPurpose.Text = Server.HtmlDecode(visitRequest.Purpose);
                txtKeyContent.Text = Server.HtmlDecode(visitRequest.KeyContent);
                var visitProduct = VisitProductPresent.GetList(p => p.VisitRequestId == visitRequest.VisitRequestId);
                for (int i = 0; i < ckbProduct.Items.Count; i++)
                {
                    foreach (var vp in visitProduct)
                    {
                        if (int.Parse(ckbProduct.Items[i].Value) == vp.ProductId)
                        {
                            ckbProduct.Items[i].Selected = true;
                        }
                    }
                    if (BasePage.PageStatus == PageStatus.Readonly)
                    {
                        ckbProduct.Items[i].Attributes.Add("disabled", "disabled");
                    }
                }
            }
        }

        public bool VisitValidateForm
        {
            get
            {
                for (int i = 0; i < ckbProduct.Items.Count; i++)
                {
                    if (ckbProduct.Items[i].Selected == true)
                    {
                        var product = ProductPresent.GetById(int.Parse(ckbProduct.Items[i].Value));
                        if (product.Status == (int)ProductStatus.Inactive)
                        {
                            cvProduct.IsValid = false;
                            cvProduct.ErrorMessage = NameResource.ProductInactive_Validation;
                            break;
                        }
                        else
                        {
                            cvProduct.IsValid = true;
                        }
                    }
                }
                if (string.IsNullOrEmpty(hfAccompanyId.Text))
                {
                    cvAccompanyName.IsValid = false;
                    cvAccompanyName.ErrorMessage = NameResource.AccompanyValidation;
                }
                int visitType1Id = string.IsNullOrEmpty(ddlVisitType1.SelectedValue) ? 0 : Convert.ToInt32(ddlVisitType1.SelectedValue);
                var visitType1 = VisitTypePresent.GetById(visitType1Id);
                if (visitType1 != null)
                {
                    if (visitType1.ParentId == 0)
                    {
                        if (string.IsNullOrEmpty(ddlVisitType2.Text))
                        {
                            cvVisitType2.IsValid = false;
                            cvVisitType2.ErrorMessage = NameResource.VisitRequest_VisitorType + CommonResource.NotNull;
                        }
                    }
                }
                if (rbtnListIsFirst.Items[1].Selected)
                {
                    var lastDate = DateTime.Today;
                    DateTime.TryParse(txtLastDate.Text, out lastDate);
                    if (lastDate == new DateTime() && !string.IsNullOrEmpty(txtLastDate.Text))
                    {
                        cvVisitDate.IsValid = false;
                        cvVisitDate.ErrorMessage = NameResource.VisitRequest_LastDate + CommonResource.ErrorFormat;
                    }
                }
                if (cvProduct.IsValid && cvAccompanyName.IsValid && cvVisitType2.IsValid && cvVisitDate.IsValid)
                    return true;
                else
                    return false;
            }
        }

        protected void Product_Update(object sender, EventArgs e)
        {
            if (flag)
            {
                int productId;
                int.TryParse(txtProduct.Text.Trim(), out productId);
                InitProductList(productId);
                flag = false;
            }
        }
        protected void btnUpdateProduct_Click(object sender, EventArgs e)
        {
            flag = true;
        }
    }
}